import argparse
import textwrap
import os
import math

def factorize(n):
    """对整数n进行质因数分解"""
    if n <= 1:
        return [n]
    
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n //= 2
    
    i = 3
    max_factor = math.isqrt(n) + 1
    while i <= max_factor and n > 1:
        while n % i == 0:
            factors.append(i)
            n //= i
            max_factor = math.isqrt(n) + 1
        i += 2
    
    if n > 1:
        factors.append(n)
    
    return factors

def analyze_and_format(input_file, output_file=None, width=73, analyze_only=False):
    """分析文件字符数量并可选地格式化文件"""
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 计算不含换行符的字符总数
        content_no_newlines = content.replace('\n', '').replace('\r', '')
        total_chars = len(content_no_newlines)
        
        # 因数分解
        factors = factorize(total_chars)
        
        # 输出分析结果
        print(f"文件: {os.path.basename(input_file)}")
        print(f"总字符数(不含换行符): {total_chars}")
        print(f"质因数分解: {' × '.join(map(str, factors))}")
        
        # 检查与73的关系
        if total_chars % width == 0:
            print(f"✓ 正好可以排列成 {total_chars//width} 行，每行{width}字符")
        else:
            full_lines = total_chars // width
            remainder = total_chars % width
            print(f"✗ 无法整除{width}: {full_lines}行完整 + {remainder}个剩余字符")
        
        # 如果不是仅分析模式，进行格式化
        if not analyze_only:
            if output_file is None:
                file_name, file_ext = os.path.splitext(input_file)
                output_file = f"{file_name}_formatted{file_ext}"
            
            # 格式化文本
            content = content.replace('\n', ' ').strip()
            formatted_content = textwrap.fill(content, width=width)
            
            # 保存结果
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(formatted_content)
            
            print(f"\n已保存格式化文件: {os.path.basename(output_file)}")
            print(f"格式化后行数: {formatted_content.count('\n') + 1}")
            
    except Exception as e:
        print(f"错误: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='字符分析与格式化工具')
    parser.add_argument('input', help='输入文件路径')
    parser.add_argument('-w', '--width', type=int, default=73, help='每行字符数（默认73）')
    parser.add_argument('-o', '--output', help='输出文件路径')
    parser.add_argument('-a', '--analyze-only', action='store_true', help='仅分析，不格式化文件')
    
    args = parser.parse_args()
    
    analyze_and_format(args.input, args.output, args.width, args.analyze_only)
